<template>
  <div class="page luckdraw-add">
    <div class="luckdraw-add-container">
      <div class="banner-section">
        <div v-if="awardImage.length">
          <swiper
            :indicator-dots="false" :autoplay="true" @change="onSwiperItemChange">
            <swiper-item v-for="(item, i) in awardImage" :key="i">
              <img :src="item || icons.awardBg" :style="imageEmptyBg" mode="aspectFill" @click="previewImg(i)"/>
            </swiper-item>
          </swiper>
          <div class="indicator">{{currentImageIndex + 1}}/{{awardImage.length}}</div>
        </div>
        <div v-else>
          <img :src="icons.awardBg" mode="aspectFill"/>
        </div>
        <a @click="onChangeImageClick">更改奖品图片</a>
      </div>
      <div class="base-section"
        v-for="(item, i) in awardList" :key="i">
        <div class="label-section" v-if="i > 0">
          <span>奖项{{i + 1}}</span>
          <i :style="minusIcon" @click="onMinusAwardListClick(i)"></i>
        </div>
        <div class="input">
          <m-input
            title="奖品名称"
            placeholder="请输入奖品名称"
            v-model="awardList[i].awardName">
          </m-input>
          <m-input
            type="number"
            title="奖品数量"
            placeholder="请输入奖品数量（个）"
            isLast
            v-model="awardList[i].awardNumber">
          </m-input>
        </div>
      </div>
      <div class="inline-btn">
        <div class="inline-btn-container" @click="onAddAwardClick">
          <i class="icon-add" :style="addIcon"></i>
          <span>添加新奖项</span>
        </div>
      </div>
      <div class="group">
        <m-link
          title="开奖条件"
          :addon="conditionList[conditionIndex]"
          @on-click="onAwardConditionLinkClick">
        </m-link>
        <m-input
          v-if="conditionIndex === 1"
          type="number"
          title="开奖人数"
          placeholder="请输入开奖人数（人）"
          v-model="awardMember">
        </m-input>
        <m-link
          v-if="conditionIndex === 0"
          title="开奖时间"
          :addon="awardTime"
          :isLast="showTimePicker"
          @on-click="onAwardTimeLinkClick">
        </m-link>
        <picker-view
          v-if="showTimePicker"
          class="award-time-picker"
          indicator-style="height:35px; background-color: transparent; border: none;"
          @change="bindTimePickerChange"
          :value="timePickerValue">
          <picker-view-column class="award-time-column1">
            <div v-for="(item, i) in rangeArr[0]" :key="i" class="award-time-item">{{item}}</div>
          </picker-view-column>
          <picker-view-column class="award-time-column2">
            <div v-for="(item, i) in rangeArr[1]" :key="i" class="award-time-item">{{item}}</div>
          </picker-view-column>
          <picker-view-column class="award-time-column3">
            <div v-for="(item, i) in rangeArr[2]" :key="i" class="award-time-item">{{item}}</div>
          </picker-view-column>
        </picker-view>
        <m-link
          title="参与条件"
          :addon="joinConditionList[joinConditionIndex]"
          isLast
          @on-click="onJoinConditionLinkClick">
        </m-link>
      </div>
      <div class="supplement-section">
        <div>
          <div class="label-section">
            <span>推荐语</span>
            <span>选填</span>
          </div>
          <div class="text">
            <textarea placeholder="请输入推荐语（60字以内）" v-model="recommend"
              placeholder-style="color:#cacaca" maxlength="60"></textarea>
          </div>
        </div>
        <div>
          <div class="label-section">
            <span>图文详情</span>
            <span v-if="tuwenDetailList.length > 0" class="color" @click="cleanTuwenStorage">清空</span>
            <span v-else>选填</span>
          </div>
          <div class="text tuwen-text">
            <div v-if="tuwenDetailList.length > 0">
              <div v-for="(item, i) in tuwenDetailList" :key="i" class="tuwen-item">
                <p v-if="item.type === 'text' && item.content">{{item.content}}</p>
                <img v-if="item.type === 'image' && item.content" :src="item.content" mode="widthFix"/>
              </div>
            </div>
            <div v-else class="inline-btn">
              <div class="inline-btn-container" @click="onAddTuwenClick">
                <i class="icon-add" :style="addIcon"></i>
                <span>添加图文详情</span>
              </div>
            </div>
          </div>
        </div>
        <div class="group">
          <m-input
            title="微信号"
            placeholder="请输入微信号（选填）"
            isLast
            v-model="wechatName">
          </m-input>
        </div>
      </div>
      <div class="btn-section">
        <div class="btn-inner">
          <m-button text="发起新抽奖" type="red" @onClick="createActivity"></m-button>
        </div>
      </div>
    </div>
    <m-toast v-model="toastContent"></m-toast>
  </div>
</template>

<script>
import MButton from 'comp/m-button'
import MInput from 'comp/m-input'
import MLink from 'comp/m-link'
import MToast from 'comp/m-toast'
import { uploadFile, getStorage, removeStorage } from '@/utils/wx'
import { apiDomain } from '@/utils/constant'
import mixins from 'comp/mixins'

const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

export default {
  mixins: [mixins],
  components: {
    MButton,
    MInput,
    MLink,
    MToast
  },
  data () {
    return {
      icons: {
        awardBg: `${require('static/images/award-bg.png')}`,
        add: `${require('static/images/add-inline.png')}`,
        minus: `${require('static/images/minus.png')}`
      },
      awardImage: [],
      currentImageIndex: 0,
      awardList: [
        {
          awardName: '',
          awardNumber: ''
        }
      ],
      awardTime: '',
      awardMember: '',
      wechatName: '',
      recommend: '',
      describe: '',
      showTimePicker: false,
      rangeArr: [],
      timePickerValue: [],
      conditionList: [
        '按时间自动开奖',
        '按人数自动开奖'
      ],
      conditionLabel: [
        '到达设定时间自动开奖',
        '3天内到达设定人数自动开奖'
      ],
      joinConditionList: [
        '无条件',
        '已绑定手机号',
        '已邀请过下级',
        '参与抽奖次数超过30次'
      ],
      joinConditionKey: [
        'none',
        'has_phone',
        'is_leader',
        'join_30'
      ],
      conditionIndex: 0,
      joinConditionIndex: 0,
      toastContent: '',
      tuwenDetailList: [],
      uploadAwardImageUrl: [],
      uploadTuwenImageUrl: []
    }
  },
  computed: {
    addIcon () {
      return `background-image: url(${this.icons.add});`
    },
    minusIcon () {
      return `background-image: url(${this.icons.minus});`
    }
  },
  mounted () {
    this.resetData()
    this.getDefaultTime()
    this.initRangeArr()
    this.cleanTuwenStorage()
  },
  async onShow () {
    this.getTuwenDetailList()
  },
  methods: {
    /**
     * 更改奖品图片
     */
    onChangeImageClick () {
      wx.chooseImage({
        count: 3,
        sizeType: ['compressed'], // 指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 返回选定照片的本地文件路径列表
          this.awardImage = res.tempFilePaths
        }
      })
    },
    /**
     * 轮播切换，更新下标
     */
    onSwiperItemChange (e) {
      this.currentImageIndex = e.mp.detail.current
    },
    /**
     * 预览图片
     */
    previewImg (i) {
      let imgArr = this.awardImage
      wx.previewImage({
        current: imgArr[i], // 当前图片地址
        urls: imgArr // 所有要预览的图片的地址集合，数组形式
      })
    },
    /**
     * 添加新奖项，只能添加3项
     */
    onAddAwardClick () {
      const awardList = this.awardList
      if (awardList.length < 3) {
        const single = {
          awardName: '',
          awardNumber: ''
        }
        this.awardList = awardList.concat(single)
      }
    },
    /**
     * 删除奖项，第一个奖项不能删除
     */
    onMinusAwardListClick (i) {
      const awardList = this.awardList
      // 删除数组某一项
      awardList.splice(i, 1)
      this.awardList = awardList
    },
    onAwardTimeLinkClick () {
      this.showTimePicker = !this.showTimePicker
    },
    /**
     * 获取默认的开奖时间，未来半小时内
     */
    getDefaultTime () {
      let str
      const date = new Date()
      if (date.getMinutes() < 30) {
        str = `${date.getMonth() + 1}月${date.getDate()}日 ${weekday[date.getDay()]} ${date.getHours()}:30`
        // 初始化的value
        this.timePickerValue = [0, date.getHours(), 1]
      } else {
        date.setHours(date.getHours() + 1)
        str = `${date.getMonth() + 1}月${date.getDate()}日 ${weekday[date.getDay()]} ${date.getHours()}:00`
        // 初始化的value
        this.timePickerValue = [0, date.getHours(), 0]
      }
      this.awardTime = str
    },
    /**
     * 初始化开奖时间选择列表
     */
    initRangeArr () {
      let arr = []

      // 日期和星期，未来一周（1+7天）
      let dateArr = []
      for (let i = 0; i < 8; i++) {
        const date = new Date()
        date.setDate(date.getDate() + i)
        dateArr[i] = `${date.getMonth() + 1}月${date.getDate()}日 ${weekday[date.getDay()]}`
      }

      // 小时
      let hourArr = []
      for (let i = 0; i < 24; i++) {
        hourArr[i] = i
      }

      arr[0] = dateArr
      arr[1] = hourArr
      arr[2] = ['00', '30']

      this.rangeArr = arr
    },
    /**
     * 选中的日期
     */
    bindTimePickerChange (e) {
      const indexArr = e.mp.detail.value
      const rangeArr = this.rangeArr
      this.awardTime = `${rangeArr[0][indexArr[0]]} ${rangeArr[1][indexArr[1]]}:${rangeArr[2][indexArr[2]]}`
      // 保存value，用于下次回显
      this.timePickerValue = indexArr
    },
    /**
     * 修改开奖条件，显示选择面板
     */
    onAwardConditionLinkClick () {
      wx.showActionSheet({
        itemList: this.conditionList,
        success: (res) => {
          this.bindConditionPickerChange(res.tapIndex)
        }
      })
    },
    /**
     * 选中开奖条件
     */
    bindConditionPickerChange (i) {
      this.conditionIndex = i
      if (i === 1) {
        this.showTimePicker = false
      }
    },
    /**
     * 修改参与条件，显示选择面板
     */
    onJoinConditionLinkClick () {
      wx.showActionSheet({
        itemList: this.joinConditionList,
        success: (res) => {
          this.bindJoinConditionPickerChange(res.tapIndex)
        }
      })
    },
    /**
     * 选中参与条件
     */
    bindJoinConditionPickerChange (i) {
      this.joinConditionIndex = i
    },
    /**
     * 添加图文详情
     */
    onAddTuwenClick () {
      wx.navigateTo({
        url: `/pages/detail-editor/main`
      })
    },
    /**
     * 获取图文详情的图片
     */
    getTuwenImage () {
      let output = []
      const tuwenDetailList = this.tuwenDetailList
      for (let i = 0; i < tuwenDetailList.length; i++) {
        if (tuwenDetailList[i].type === 'image' && tuwenDetailList[i].content) {
          output.push(tuwenDetailList[i].content)
        }
      }
      return output
    },
    /**
     * 检查并上传图片
     */
    async checkImageUpload () {
      const tuwenImage = this.getTuwenImage()
      const awardImage = this.awardImage
      let uploadAwardImageUrl = []
      let uploadTuwenImageUrl = []

      if (awardImage.length) {
        // 上传奖品的图片
        for (let i = 0; i < awardImage.length; i++) {
          const uploadResult = await uploadFile({
            url: `${apiDomain}/api/file/img`,
            filePath: awardImage[i],
            name: 'file',
            formData: {
              'type': 'luckdraw:award'
            }
          })
          if (uploadResult.statusCode !== 200) {
            wx.showModal({
              title: '提示',
              content: '上传失败，请重试',
              showCancel: false
            })
            return false
          }
          const data = JSON.parse(uploadResult.data)
          const realImageUrl = data && data.result && data.result.img
          uploadAwardImageUrl[i] = realImageUrl
        }
      }
      if (tuwenImage.length) {
        // 上传图文详情的图片
        for (let i = 0; i < tuwenImage.length; i++) {
          const uploadResult = await uploadFile({
            url: `${apiDomain}/api/file/img`,
            filePath: tuwenImage[i],
            name: 'file',
            formData: {
              'type': 'luckdraw:award'
            }
          })
          if (uploadResult.statusCode !== 200) {
            wx.showModal({
              title: '提示',
              content: '上传失败，请重试',
              showCancel: false
            })
            return false
          }
          const data = JSON.parse(uploadResult.data)
          const realImageUrl = data && data.result && data.result.img
          uploadTuwenImageUrl[i] = realImageUrl
        }
      }
      this.uploadAwardImageUrl = uploadAwardImageUrl
      this.uploadTuwenImageUrl = uploadTuwenImageUrl
      return true
    },
    /**
     * 获取图文详情的上传数据，含真实的图片路径
     */
    getTuwenDetailUploadList () {
      const tuwenDetailList = this.tuwenDetailList
      const uploadTuwenImageUrl = this.uploadTuwenImageUrl
      if (uploadTuwenImageUrl.length > 0) {
        let k = 0
        for (let i = 0; i < tuwenDetailList.length; i++) {
          if (tuwenDetailList[i].type === 'image' && tuwenDetailList[i].content) {
            tuwenDetailList[i].content = uploadTuwenImageUrl[k]
            k++
          }
        }
      }
      return tuwenDetailList
    },
    /**
     * 创建活动，step1 上传图片（如有图片）
     */
    async createActivity () {
      if (!this.checkForm()) {
        return
      }
      const ret = await this.$store.dispatch('queryConfig')
      wx.showModal({
        title: '提示',
        content: `发起抽奖将消耗${ret.goldCreatedActivity}个金币`,
        showCancel: true,
        success: () => {
          this.submitActivity()
        }
      })
    },
    /**
     * 创建活动，step2 提交活动
     */
    async submitActivity () {
      const uploadResult = await this.checkImageUpload()
      if (!uploadResult) {
        return
      }
      const openId = await this.getOpenId()
      let postData = {
        createrId: openId,
        // 是否高级版 0基本,1高级
        isAdvanced: 1,
        // 奖项一
        awardTitle: this.awardList[0].awardName,
        awardAmount: parseInt(this.awardList[0].awardNumber),
        awardImage: this.uploadAwardImageUrl[0],
        // 奖项二
        awardTitleSecond: this.awardList[1] ? this.awardList[1].awardName : '',
        awardAmountSecond: this.awardList[1] ? parseInt(this.awardList[1].awardNumber) : '',
        awardImageSecond: this.uploadAwardImageUrl[1],
        // 奖项三
        awardTitleThird: this.awardList[2] ? this.awardList[2].awardName : '',
        awardAmountThird: this.awardList[2] ? parseInt(this.awardList[2].awardNumber) : '',
        awardImageThird: this.uploadAwardImageUrl[2],
        info: JSON.stringify({
          wechatName: this.wechatName
        }),
        recommend: this.recommend
      }
      if (this.conditionIndex === 0) {
        // 按到时间抽奖
        postData = {
          ...postData,
          type: 1,
          awardTime: this.handleAwardTime()
        }
      } else {
        // 按满人数抽奖
        postData = {
          ...postData,
          type: 2,
          awardPeople: parseInt(this.awardMember)
        }
      }
      if (this.joinConditionIndex !== 0) {
        // 扩容，包括奖品图片、参与条件、图文详情
        postData = {
          ...postData,
          data: JSON.stringify({
            awardImageList: this.uploadAwardImageUrl,
            joinCondition: [{
              key: this.joinConditionKey[this.joinConditionIndex],
              value: this.joinConditionList[this.joinConditionIndex]
            }],
            tuwenDetail: this.getTuwenDetailUploadList()
          })
        }
      } else {
        // 扩容，包括奖品图片、参与条件、图文详情
        postData = {
          ...postData,
          data: JSON.stringify({
            awardImageList: this.uploadAwardImageUrl,
            tuwenDetail: this.getTuwenDetailUploadList()
          })
        }
      }
      const res = await this.$store.dispatch('createActivity', postData)
      wx.navigateTo({
        url: `/pages/add-result/main?activityId=${res.result.activity_id}`
      })
    },
    /**
     * 开奖时间格式化为秒
     */
    handleAwardTime () {
      // 2013/3/8 17:20
      const awardTime = this.awardTime
      const lit = awardTime.split(' ')
      const date = lit[0]
      const time = lit[2]

      const month = date.split('月')[0]
      const day = (date.split('月')[1]).split('日')[0]

      const _date = new Date()
      const year = _date.getFullYear()

      const str = `${year}/${month}/${day} ${time}`
      const output = (new Date(str)).getTime() / 1000

      return output
    },
    /**
     * 表单校验
     */
    checkForm () {
      // 奖项判断，如果新增了奖项，则要填写完整才能提交
      const awardList = this.awardList
      let awardNumber = 0
      for (let i = 0; i < awardList.length; i++) {
        if (!awardList[i].awardName) {
          this.toastContent = i === 0 ? '请输入奖品名称' : `请输入奖品${i + 1}名称`
          return false
        }
        if (!awardList[i].awardNumber) {
          this.toastContent = i === 0 ? '请输入奖品数量' : `请输入奖品${i + 1}数量`
          return false
        }
        awardNumber += parseInt(awardList[i].awardNumber)
      }
      // 开奖条件判断
      if (this.conditionIndex === 1) {
        if (!this.awardMember) {
          this.toastContent = '请输入开奖人数'
          return false
        }
        if (parseInt(this.awardMember) < parseInt(awardNumber)) {
          this.toastContent = '开奖人数不能小于奖品总数量'
          return false
        }
      }
      if (this.conditionIndex === 0) {
        if (!this.awardTime) {
          this.toastContent = '请选择开奖时间'
          return false
        }
        const awardTime = this.handleAwardTime()
        const date = new Date().getTime() / 1000
        if (awardTime <= date) {
          this.toastContent = '开奖时间不能早于当前时间'
          return false
        }
      }
      return true
    },
    /**
     * 获取缓存里的图文详情
     */
    async getTuwenDetailList () {
      try {
        const editContent = await getStorage('editContent')
        this.tuwenDetailList = JSON.parse(editContent)
      } catch (e) {
        console.log(e)
      }
    },
    /**
     * 清空图文详情
     */
    cleanTuwenStorage () {
      this.tuwenDetailList = []
      removeStorage('editContent')
    }
  }
}
</script>

<style lang="less" scoped>
.luckdraw-add {
  &-container {
    padding-bottom: 30rpx;
  }
  .group {
    margin-top: 20rpx;
  }
  .banner-section {
    position: relative;
    img {
      display: block;
      width: 100%;
      height: 400rpx;
    }
    a {
      display: block;
      position: absolute;
      top: 14rpx;
      right: 14rpx;
      font-size: 28rpx;
      color: #333;
      text-align: center;
      background-color: #fff;
      border: 1rpx solid #575757;
      padding: 16rpx 20rpx;
      &:active {
        background: #d8d8d8;
      }
    }
    swiper {
      height: 400rpx;
    }
    .indicator {
      position: absolute;
      right: 30rpx;
      bottom: 30rpx;
      padding: 0 18rpx;
      font-size: 24rpx;
      color: #fff;
      background-color: rgba(0, 0, 0, 0.6);
      line-height: 44rpx;
      border-radius: 22rpx 22rpx;
    }
  }
  .base-section {
    .label-section {
      padding-bottom: 20rpx;
    }
  }
  .inline-btn {
    display: flex;
    justify-content: center;
    color: #686868;
    font-size: 28rpx;
    padding: 50rpx 0;
    &-container {
      display: flex;
      align-items: center;
      padding: 16rpx 30rpx;
      border: 1rpx solid #686868;
      &:active {
        background: #d8d8d8;
      }
    }
    i {
      display: block;
      width: 24rpx;
      height: 24rpx;
      background-size: contain;
      background-repeat: no-repeat;
      background-position: center center;
      margin-right: 10rpx;
    }
  }
  .label-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 40rpx 30rpx 0;
    font-size: 30rpx;
    color: #777;
    i {
      display: block;
      width: 40rpx;
      height: 40rpx;
      background-size: contain;
      background-repeat: no-repeat;
      background-position: center center;
    }
    .color {
      color: #e0382f;
    }
  }
  .award-time-picker {
    width: 100%;
    height: 360rpx;
    border-top: 1rpx solid #e6ebf0;
    font-size: 30rpx;
    text-align: center;
    margin-bottom: 20rpx;
  }
  .award-time-column1 {
    flex: 2;
  }
  .award-time-column2, .award-time-column3 {
    flex: 1;
  }
  .award-time-item {
    height: 70rpx;
    line-height: 70rpx;
  }
  .award-condition-picker {
    width: 100%;
    height: 240rpx;
    border-top: 1rpx solid #e6ebf0;
    font-size: 30rpx;
    text-align: center;
    margin-bottom: 20rpx;
  }
  .award-condition-column1 {
    flex: 1;
  }
  .award-condition-item {
    height: 70rpx;
    line-height: 70rpx;
  }
  .supplement-section {
    .inline-btn {
      padding: 58rpx 0;
    }
    .text {
      margin-top: 20rpx;
      padding: 30rpx 30rpx;
      background-color: #fff;
      textarea {
        width: 100%;
        font-size: 32rpx;
        color: #333;
        line-height: 1.5;
        height: 192rpx;
      }
      p {
        font-size: 32rpx;
        line-height: 1.5;
      }
      img {
        display: block;
        width: 100%;
      }
      &.tuwen-text {
        color: #333;
        .tuwen-item {
          img, p {
            padding-bottom: 30rpx;
          }
          &:last-child {
            img, p {
              padding-bottom: 0;
            }
          }
        }
      }
    }
  }
  .btn-section {
    width: 100%;
    margin-top: 30rpx;
    .btn-inner {
      padding: 20rpx 20rpx;
    }
  }
}
</style>
